<template>
  <view class="inbound-create-container">
    <uni-forms ref="form" :model="formData" :rules="rules" class="form-container">
      <uni-forms-item label="项目名称" name="projectId" class="form-item">
        <uni-data-select v-model="formData.projectId" :localdata="project_list" @change="handleProjectChange" />
      </uni-forms-item>
      <uni-forms-item label="出行方式" name="transportType" class="form-item">
        <uni-data-select v-model="formData.transportType" :localdata="transport_type" />  
      </uni-forms-item>
      
      <!-- 只有当出行方式为"公司车辆"时才显示备选车辆 -->
      <uni-forms-item v-if="formData.transportType === '1'" label="备选车辆" name="bookLicensePlate" class="form-item">
        <uni-data-select v-model="formData.bookLicensePlate" :localdata="car_list" />
      </uni-forms-item>
           
      <!-- 动态产品列表 -->
      <view v-if="formData.projectId" class="products-container">
        <view v-for="(product, index) in formData.storeOrderCargoList" :key="index" class="product-item">
          <uni-forms-item :label="'产品名称' + (index + 1)" :name="'products.' + index + '.name'" class="form-item">
            <uni-easyinput v-model="product.cargoName" placeholder="请输入产品名称" disabled />
          </uni-forms-item>
          <uni-forms-item :label="'数量' + (index + 1)" :name="'products.' + index + '.quantity'" class="form-item">
            <uni-number-box v-model="product.cargoNum" :min="0" :max="product.cargoInputNum" />
          </uni-forms-item>          
        </view>
      </view>

      
      <uni-forms-item label="取货司机" name="driver" class="form-item">
        <uni-data-select v-model="formData.driver" :localdata="driver_list" />
      </uni-forms-item>
      
      <uni-forms-item label="备注" name="remark" class="form-item">
        <uni-easyinput v-model="formData.remark" type="textarea" placeholder="请输入备注信息" />
      </uni-forms-item>
    </uni-forms>
    
    <view class="button-group">
      <button class="submit-btn" @click="submitForm">保存订单</button>
      <button class="reset-btn" @click="resetForm">重置</button>
    </view>
  </view>
</template>

<script>
import { addOrder} from "@/api/mes/order"
import { listCar } from "@/api/mes/car"
import { listProjectExtend } from "@/api/mes/projectExtend"
import { getDicts } from "@/api/system/dict/data" // 引入字典API
import { listDriver,listProjectCargo } from "@/api/mes/projectExtend"
export default {
  data() {
    return {
      driver_list: [],
      maxCot:100,
      projectName: null,
      car_list: [],
      project_list: [],
      project_detail: {},
      // 字典数据
      transport_type: [],
      order_status: [],
      formData: {
        storeOrderCargoList: [] // 确保初始化时包含这个数组
      },
      rules: {
        projectId: {
          rules: [{ required: true, errorMessage: '请选择项目名称' }]
        },
        bookLicensePlate: {
          rules: [{ required: true, errorMessage: '请选择备选车辆' }]
        },
        transportType: {
          rules: [{ required: true, errorMessage: '请选择出行方式' }] 
        },
        driver: {
          rules: [{ required: true, errorMessage: '请选择司机' }]
        }
      }
    }
  },
  onLoad() {
    this.getProjectList();
    this.getCarList();
    this.getDictData(); // 获取字典数据
    this.getDriverList(); // 获取司机列表
  },
  methods: {
    getDriverList() {
      listDriver().then(response => {
        this.driver_list = response.data.map(driver => ({
          value: driver.userId.toString(),
          text: driver.nickName
        }));
      }); 
    },
    handleProjectChange(value) {
      if (!value) return;
      
      uni.showLoading({
        title: '加载中...'
      });
      
      listProjectCargo({projectId: value, orderType: 1}).then(response => {
        if (response.data && Array.isArray(response.data)) {
          this.formData.storeOrderCargoList = response.data.map(product => ({
            cargoName: product.cargoName,
            cargoInputNum: product.cargoInputNum,
            cargoNum: product.cargoInputNum,
          }));
          
          // 强制更新视图
          this.$forceUpdate();
        } else {
          this.formData.storeOrderCargoList = [];
        }
      }).catch(error => {
        console.error('获取项目货物失败', error);
        uni.showToast({
          title: '获取项目货物失败',
          icon: 'none'
        });
      }).finally(() => {
        uni.hideLoading();
      });
    },
    submitForm() {
      this.$refs.form.validate().then(res => {
        // 显示加载提示
        uni.showLoading({
          title: '提交中...',
          mask: true
        });
        this.formData.orderType = 1;
        // 提交数据
        addOrder(this.formData)
          .then(response => {
            if (response.code === 200) {
              uni.showToast({
                title: '提交成功',
                icon: 'success'
              });
              uni.navigateBack({
              delta: 1,
              success: function() {
                // 获取当前页面栈
                const pages = getCurrentPages();
                // 获取上一页实例
                const prevPage = pages[pages.length - 1];
                // 调用上一页的刷新方法
                if (prevPage && prevPage.$vm && typeof prevPage.$vm.getList === 'function') {
                  prevPage.$vm.getList();
                }
              }
            });
            } else {
              throw new Error(response.msg || '提交失败');
            }
          })
          .catch(error => {
            console.error('提交失败：', error);
            uni.showToast({
              title: error.message || '提交失败，请重试',
              icon: 'error'
            });
          })
          .finally(() => {
            uni.hideLoading(); // 确保在任何情况下都关闭loading
          });
      }).catch(err => {
        // 表单验证失败
        console.error('表单验证失败：', err);
        uni.hideLoading(); // 表单验证失败时也要关闭loading
        uni.showToast({
          title: '请检查必填项',
          icon: 'none'
        });
      });
    },
    resetForm() {
      // 重置表单数据
      this.formData = {
        storeOrderCargoList: [] // 确保重置时包含这个数组
      }
      // 重置表单校验状态
      if (this.$refs.form && typeof this.$refs.form.resetFields === 'function') {
        this.$refs.form.resetFields()
      } else {
        // 针对小程序环境，手动清除校验状态
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      }
      // 提示用户
      uni.showToast({
        title: '已重置',
        icon: 'none'
      })
    },
    getProjectList() {
        listProjectExtend({orderType:1}).then(response => {
          this.project_list = response.data.map(project => ({
            value: project.projectId.toString(),
            text: project.projectName,
          }));
    });
    },
    getCarList() {
      listCar().then(response => {
        this.car_list = response.data.map(car => ({
              value: car.carId,
              text:  car.carNo,
            }));
      });
    },
    getDictData() {
      getDicts('transport_type').then(response => {
        this.transport_type = response.data.map(item => ({
          value: item.dictValue,
          text: item.dictLabel
        }));
      });
      getDicts('order_status').then(response => {
        this.order_status = response.data
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.inbound-create-container {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  
  .form-container {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
    margin-bottom: 30rpx;
    
    .form-item {
      margin-bottom: 24rpx;
      
      :deep(.uni-forms-item__label) {
        font-size: 28rpx;
        color: #333;
        padding: 0 12rpx;
      }
      
      :deep(.uni-easyinput__content) {
        min-height: 72rpx;
        background-color: #f8f8f8;
        border-radius: 8rpx;
        
        input {
          font-size: 28rpx;
        }
      }
      
      :deep(.uni-data-select) {
        .uni-select--mask {
          background-color: #f8f8f8;
          border-radius: 8rpx;
        }
        
        .uni-select__input-text {
          font-size: 28rpx;
        }
      }
    }
  }
  
  .products-container {
    .product-item {
      margin: 20rpx 0;
      padding: 20rpx;
      background-color: #f8f8f8;
      border-radius: 8rpx;
    }
  }
  
  .button-group {
    margin-top: 40rpx;
    padding: 0 20rpx;
    
    .submit-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      background-color: #007AFF;
      color: #fff;
      font-size: 32rpx;
      border-radius: 44rpx;
      margin-bottom: 20rpx;
    }
    
    .reset-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      background-color: #F1F1F1;
      color: #333;
      font-size: 32rpx;
      border-radius: 44rpx;
    }
  }
}
</style>